module.exports = {
  up: async (queryInterface, Sequelize) => {
    // 先检查列是否已存在
    const tableInfo = await queryInterface.describeTable('plans');
    
    // 添加新字段（如果不存在）
    if (!tableInfo.code) {
      await queryInterface.addColumn('plans', 'code', {
        type: Sequelize.STRING(50),
        allowNull: true,
      });
      
      // 为现有记录生成唯一的 code
      await queryInterface.sequelize.query(`
        UPDATE plans 
        SET code = CONCAT('plan_', SUBSTRING(id, 1, 8))
        WHERE code IS NULL
      `);
      
      // 现在设置为非空和唯一
      await queryInterface.changeColumn('plans', 'code', {
        type: Sequelize.STRING(50),
        allowNull: false,
        unique: true,
      });
    }

    if (!tableInfo.price) {
      await queryInterface.addColumn('plans', 'price', {
        type: Sequelize.DECIMAL(10, 2),
        allowNull: false,
        defaultValue: 0,
      });
      
      // 从 price_monthly 复制数据
      await queryInterface.sequelize.query(`
        UPDATE plans SET price = price_monthly WHERE price = 0
      `);
    }

    if (!tableInfo.billing_cycle) {
      await queryInterface.addColumn('plans', 'billing_cycle', {
        type: Sequelize.ENUM('monthly', 'yearly'),
        allowNull: false,
        defaultValue: 'monthly',
      });
    }

    if (!tableInfo.max_users) {
      await queryInterface.addColumn('plans', 'max_users', {
        type: Sequelize.INTEGER,
        allowNull: true,
      });
    }

    if (!tableInfo.max_storage) {
      await queryInterface.addColumn('plans', 'max_storage', {
        type: Sequelize.BIGINT,
        allowNull: true,
      });
    }

    // 添加索引（如果不存在）
    try {
      await queryInterface.addIndex('plans', ['code'], {
        name: 'plans_code_idx',
      });
    } catch (e) {
      // 索引可能已存在，忽略错误
    }
  },

  down: async (queryInterface) => {
    const tableInfo = await queryInterface.describeTable('plans');
    
    if (tableInfo.max_storage) {
      await queryInterface.removeColumn('plans', 'max_storage');
    }
    if (tableInfo.max_users) {
      await queryInterface.removeColumn('plans', 'max_users');
    }
    if (tableInfo.billing_cycle) {
      await queryInterface.removeColumn('plans', 'billing_cycle');
    }
    if (tableInfo.price) {
      await queryInterface.removeColumn('plans', 'price');
    }
    if (tableInfo.code) {
      await queryInterface.removeColumn('plans', 'code');
    }
  },
};

